package me.firstapp.service.weixin.activity.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import me.firstapp.common.exception.ServiceException;
import me.firstapp.module.weixin.activity.RedPackRecord;
import me.firstapp.module.weixin.order.ProductOrder;
import me.firstapp.repository.weixin.activity.RedPackRecordRepository;
import me.firstapp.service.weixin.activity.RedPackRecordService;

@Service
public class RedPackRecordServiceImpl implements RedPackRecordService {

	@Autowired
	private RedPackRecordRepository redPackRecordRepository;

	@Override
	public RedPackRecord executeAddRedPackRecord(ProductOrder productOrder) {
		if (null == productOrder) {
			return null;
		}
		RedPackRecord redPackRecord = redPackRecordRepository.findByProductIdAndOpenId(productOrder.getProductId(),
				productOrder.getOpenId());
		if (null != redPackRecord) {
			throw new ServiceException("error", "你已经兑换过，只可兑换一次！");
		}
		redPackRecord = new RedPackRecord();
		redPackRecord.setProductId(productOrder.getProductId());
		redPackRecord.setOpenId(productOrder.getOpenId());
		redPackRecordRepository.save(redPackRecord);

		return redPackRecord;
	}

	@Override
	public RedPackRecord findByProductIdAndOpenId(Long productId, String openId) {
		return redPackRecordRepository.findByProductIdAndOpenId(productId, openId);
	}

}
